package com.struggle.myrabbitmq.sample.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.struggle.myrabbitmq.sample.MyRabbitConstants;
import com.struggle.myrabbitmq.util.ConnectionUtil;
import lombok.SneakyThrows;

import java.io.IOException;

/**
 * @className Receive2
 * @Description work模式：rabbitMQ消费者1
 * @Author liuwj3
 * @Date 2019/9/19 0019 下午 3:48
 **/
public class Receive2 {

    public static void main(String[] args) throws IOException, InterruptedException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(MyRabbitConstants.QUEUE_NAME_WORK, false, false, false, null);
        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        // rabbitmq 3.4.1版本写法
        /*// 定义队列的消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列 b:true表示自动应答，false表示手动应答（channel.basicAck）
        channel.basicConsume(MyRabbitConstants.QUEUE_NAME_WORK, false, consumer);

        // 获取消息
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println(" [y] Received '" + message + "'");
            //休眠
            Thread.sleep(1000);

            // 返回确认状态，注释的话表示使用自动确认模式，开启表示使用手动确认模式
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }*/

        // rabbitmq 4.x版本后写法
        DeliverCallback callback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody());
            System.out.println(" [y] Received '" + message + "'");
            //休眠
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();
            }
            // 返回确认状态，注释的话表示使用自动确认模式，开启表示使用手动确认模式
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };
        // false为手动确认
        channel.basicConsume(MyRabbitConstants.QUEUE_NAME_WORK, false, callback, consumerTag -> {
        });

    }
}
